package train;

import org.junit.Before;
import org.junit.Test;

import java.util.*;
import java.util.stream.Collector;
import java.util.stream.Collectors;

/**
 * @description:
 * @author: yexc
 * @date: 2018-12-23 14:20
 */
public class Train {
    //https://blog.csdn.net/nullbull/article/details/81234250

    List<Transaction> transactions;

    @Before
    public void init(){
        Trader raoul = new Trader("Raoul", "Cambridge");
        Trader mario = new Trader("Mario","Milan");
        Trader alan = new Trader("Alan","Cambridge");
        Trader brian = new Trader("Brian","Cambridge");

        transactions = Arrays.asList(
                new Transaction(brian, 2011, 300),
                new Transaction(raoul, 2012, 1000),
                new Transaction(raoul, 2011, 400),
                new Transaction(mario, 2012, 710),
                new Transaction(mario, 2012, 700),
                new Transaction(alan, 2012, 950)
        );
    }

    //找出2011年发生的所有交易，并按交易额排序
    @Test
    public void t1(){
        List<Transaction> collect = transactions.stream().filter(trader -> (trader.getYear() == 2011))
                .sorted(Comparator.comparingInt(Transaction::getValue).reversed()).collect(Collectors.toList());
        collect.stream().forEach(System.out::println);
    }


    //交易员在哪些不同的城市工作过
    @Test
    public void t2(){
        transactions.stream()
                .map(Transaction::getTrader)
                .map(Trader::getCity)
                .collect(Collectors.toSet())
                .forEach(System.out::println);
    }


    //查找所有来自剑桥的交易员，并按姓名排序
    @Test
    public void t3(){
        transactions.stream()
                .map(Transaction::getTrader)
                .filter(trader -> trader.getCity().equals("Cambridge"))
                .distinct()
                .sorted(Comparator.comparing(Trader::getName))
                .forEach(System.out::println);
    }

    //有没有交易员在米兰工作的？
    @Test
    public void t4(){
        boolean milan = transactions.stream()
                .anyMatch(transaction -> transaction.getTrader().getCity().equals("Milan"));
        System.out.println(milan);
    }

    //打印生活在剑桥的交易员的所有交易额
    @Test
    public void t5(){
        Map<Trader, List<Transaction>> cambridge = transactions.stream()
                .filter(transaction -> transaction.getTrader().getCity().equals("Cambridge"))
                .collect(Collectors.groupingBy(Transaction::getTrader));
        System.out.println(cambridge);
    }

    //所有交易中，最高的交易额是多少
    @Test
    public void t6(){
        Optional<Integer> max = transactions.stream().map(Transaction::getValue).max(Integer::compareTo);
        System.out.println(max.get());
    }

    //找到交易额最小的交易
    @Test
    public void t7(){
        transactions.stream().sorted(Comparator.comparing(Transaction::getValue)).limit(1).forEach(System.out::println);
    }


}
